//
//  WBUserAccount.swift
//  SinaWeibo
//
//  Created by 美食家 on 17/4/10.
//  Copyright © 2017年 不孤独的美食家. All rights reserved.
//

import UIKit

private var accountFile : NSString = "userAccount.json"

class WBUserAccount: NSObject {
    
    /// 访问令牌
    var access_token : String? // ="2.00v8tSKEGdgIAD0b8d8c538d0GidEK"
    /// 用户 ID
    var uid : String?
    /// 过期时间 开发者五年，用户3天
    var expires_in : TimeInterval = 0{
        didSet{
           expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 登陆过期时间
    var expiresDate : Date?
    /// 用户昵称
    var screen_name : String?
    /// 用户头像地址大图，180X180像素
    var avatar_large : String?
    
    override var description: String{
    
         return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        guard let path = accountFile.cz_appendDocumentDir(),
              let data = NSData(contentsOfFile : path),
              let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : AnyObject] else {
            return
        }
        /** 用户登陆是否成功的关键代码 */
        self.yy_modelSet(with: dict ?? [:])
        
        //测试判断是否过期
//        expiresDate = Date(timeIntervalSinceNow: -3600*24)
        //判断token是否过期
        if expiresDate?.compare(Date()) != .orderedDescending{
            print("账户过期，请重新登录")
            access_token = nil
            uid = nil
         //删除账户文件
            _ = try? FileManager.default.removeItem(atPath:path)
        }
    }
    
    func saveAccount(){
        
        var dict = self.yy_modelToJSONObject() as? [String:AnyObject] ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
              let filePath = accountFile.cz_appendDocumentDir() else {
            return
        }
        
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("\(filePath)")
    
    }

}
